<template>
	<m-layout title="商品详情" gap="0 " :isShow="false" :scrollTop="scrollTop">
		<!-- 顶部操作栏 -->
		<view class="header-top" :style="{ background: topStyle }">
			<view class="nav flex-between">
				<m-icon size="34" type="icon-fanhui" @click="Jump()"></m-icon>
				<template v-if="scrollTop > 0">
					<view class="tables" :style="{ opacity: topOpt }">
						<text :class="{ active: scrollIdx == 0 }" @click="tapScrollFn(0)">宝贝</text>
						<text :class="{ active: scrollIdx == 1 }" @click="tapScrollFn(1)">详情</text>
					</view>
				</template>
				<m-icon type="icon-fenxiang1" wh="50" @click="$refs.sharPopup.open()"></m-icon>
			</view>
		</view>
		<view class="image-box">
			<image :src="goodsInfo.picurl" mode="widthFix"></image>
		</view>
		<m-block gap="10 24 24" spa="20 24">
			<view class="flex-between">
				<view class="flex">
					<m-number :cny="goodsInfo.coinid != 2" :value="goodsInfo.price" isOmit size="60 42" weight="700"
						color="var(--theme)"></m-number>
					<m-text v-if="goodsInfo.coinid  == 2" ftsize="32" spa="12 0 0 10" color="var(--theme)">积分</m-text>
					
					
					<!-- 
					<m-text color="#999" spa="12 0 0 30" decoration="line-through">
						原价：{{goodsInfo.marketPrice}}</m-text> -->
				</view>
				
				<view class="flex" style="text-decoration: line-through;">
					<m-text color="var(--theme)" spa="22 0 0 0" decoration="line-through"> 原价：</m-text> 
					<m-number spa="22 0 0 " :cny="goodsInfo.coinid != 2" unit="积分" :value="goodsInfo.marketPrice"  color="var(--theme)"></m-number>
				</view>
				
				<!-- <m-icon type="icon-shoucang" wh="50" :color="isCollection?'var(--theme)':'#999'" @click="collection"></m-icon> -->
				<!-- <m-text ftsize="26" gap="20 0 0 15" color="#999" style="text-decoration: line-through">¥{{attr.marketprice || 0}}</m-text> -->
			</view>
			<m-text gap="15 0 " class="des" block ftsize="30" weight="600" :text="goodsInfo.goodsName" />
			<m-text gap="15 0 " block color="#999" :text="goodsInfo.sketch" />
			<m-line spa="20 0 10"></m-line>
			<view class="flex-between">
				<m-text gap="15 0 0" class="des" color="#666666" block ftsize="24">总销量：{{goodsInfo.totalSell}}</m-text>
				<m-text gap="15 0 0" class="des" color="#666666" block ftsize="24">库存：{{goodsInfo.stock}}</m-text>
			</view>
		</m-block>
		<m-block gap="0 24" spa="0 24">
			<!-- <m-cell title="偏远地区不发货" rIcon="" leftWidth="140" gap="24 0" v-if="goodsInfo.sendext > 0">
				<m-text ftsize='28' weight="600" slot="left">发货</m-text>
				<m-text slot="center"></m-text>
			</m-cell> -->
			<m-cell :title="yftitle" rIcon="" leftWidth="140" gap="24 0">
				<m-text ftsize='28' weight="600" slot="left">快递</m-text>
			</m-cell>
			<m-cell leftWidth="140" gap="24 0" @click="Jump('/pagesA/mine/address/address?isSelect=true')">
				<m-text ftsize='28' weight="600" slot="left">配送至</m-text>
				<template v-if="nowId && address.are">
					<m-text ftsize='28' slot="center" :text=" address.are"></m-text>
				</template>
				<template v-else>
					<m-text ftsize='28' slot="center">未选择收货地址</m-text>
				</template>
			</m-cell>
			<template v-if="attr.length > 1">
				<m-cell leftWidth="140" border="0" gap="24 0" @click="$refs.popup.open()">
					<m-text ftsize='28' weight="600" slot="left">规格</m-text>
					<template v-if="goodsInfo['stock'] <= 0">
						<m-text ftsize='28' slot="center">当前商品库存不足</m-text>
					</template>
					<template slot="center" v-else>
						<m-text ftsize='28' :text="`已选：${defaultSelected.join('-')}`"></m-text>
					</template>
				</m-cell>
			</template>
			<m-cell :title="nowHeads['trueName']" leftWidth="140" gap="24 0" @click="$refs.headsPopup.open()">
				<m-text ftsize='28' weight="600" slot="left">团长</m-text>
			</m-cell>
		</m-block>
		<m-block radius="0" spa="20 0" class="goodsDescription">
			<m-text block bold gap="20 24" ftsize="32">商品详情</m-text>
			<view class="html-main" v-html="goodsInfo.content">
			</view>
		</m-block>

		<view class="footer flex-between">
			<view class="left flex-between">
				<view class="box" @click="Jump({ url: '/', mode: 4 })">
					<m-icon type="icon-shouye" wh="40"></m-icon>
					<text class="box-text">首页</text>
				</view>
			</view>
			<view class="left flex-between">
				<uni-badge class="uni-badge-left-margin" :text="cartLengh || 0" absolute="rightTop" :offset="[3, 3]"
					size="small">
					<view class="box" @click="Jump({ url: '/pages/cart/cart', mode: 4 })">
						<m-icon type="icon-gouwuche1" wh="40"></m-icon>
						<text class="box-text">购物车</text>
					</view>
				</uni-badge>
			</view>
			<view class="left flex-between">
				<view class="box" @click="openUrl({url:config715})">
					<m-icon type="icon-kefu" wh="40"></m-icon>
					<text class="box-text">客服</text>
				</view>
			</view>

			<view class="flex-1 right flex-between">
				<template v-if="goodsInfo.gtype != 2">
					<m-button :loading='cartLoading' @click="addCart" style="flex: 1;margin-right: 20rpx;" radius="8"
						bgColor="#F6F7F9" color="#333" gap="22 0">
						加入购物车
					</m-button>
				</template>
				<template v-if="attr.length > 1">
					<m-button @click="$refs.popup.open()" style="flex: 1.2;" bgColor="var(--theme)" radius="8"
						gap="22 0">立即购买</m-button>
				</template>
				<template v-else>
					<m-button @click="goPay" :disabled="payButton" :type="payButton ? 'theme' : 'disable'"
						style="flex: 1.2;" bgColor="var(--theme)" radius="8" gap="22 0">立即购买</m-button>
				</template>
			</view>
		</view>
		<view class="" style="display: none;">
			<specs-section v-model="selectedUnit" :units="attr"></specs-section>
		</view>
		<!-- 规格弹框 -->
		<uni-popup ref="popup" type="bottom">
			<m-block class="popup-goods" gap="22 24" radius="20 20 0 0">
				<view class="goods-info flex-between">
					<view class="left">
						<m-image wh="150" :src="goodsInfo.picurl" />
					</view>
					<view class="right flex-column flex-around">
						<view class="h1 flex">
							<view class="des otp2">
								{{goodsInfo.goodsName}}
							</view>
							<!-- 积分商城商品 -->
						</view>
						<view class="flex">
							<m-number :cny="goodsInfo.coinid != 2" unit="积分" :value="goodsInfo.price" :isOmit="false"
								color="#F95F5F" size="48 28"></m-number>
						</view>
						<template v-if="goodsInfo['stock'] > 0">
							<text class="stock">库存 {{ goodsInfo['stock'] }}</text>
						</template>
						<template v-else>
							<text class="stock">库存不足</text>
						</template>
					</view>
				</view>
				<view class="spec-box">
					<!-- 规格选择区域 -->
					<specs-section v-model="selectedUnit" :defaultSelected="defaultSelected"
						:units="attr"></specs-section>
				</view>

				<view class="amount flex-between mtb-36">
					<text>数量</text>
					<uni-number-box v-model="buycount" :min="1" :max="goodsInfo['stock']" @change="changeValue" />
				</view>
				<view class="btn-box flex-between">
					<m-button style="margin-right: 20rpx;" class="flex-1" block bgColor="#F6F7F9" color="#333"
						gap="22 0" :loading='cartLoading' @click="addCart(2)">
						加入购物车
					</m-button>
					<m-button class="flex-1" block @click="goPay" :type="payButton ? 'theme' : 'disable'"
						:disabled="payButton">立即购买</m-button>
				</view>
			</m-block>
		</uni-popup>
		<uni-popup ref="headsPopup" type="bottom">
			<m-block class="popup-heads" gap="22 24" radius="20 20 0 0">
				<view class="flex-between">
					<m-text></m-text>
					<m-text>选择团长</m-text>
					<m-icon type="icon-guanbi"></m-icon>
				</view>
				<template v-for="(item,idx) in heads">
					<view class="li flex-between" :key="idx" @click="nowHeads = item;$refs.headsPopup.close()">
						<m-image :src="item.headpic" wh="114" radius="20" spa="0 20 0 0"></m-image>
						<view class="flex-1">
							<m-text block bold ftsize="28">团长：{{item.trueName}}</m-text>
							<m-text block color="#999999" spa="20 0 0">服务区域：{{item.province}} {{ item.city}}
								{{ item.district}}</m-text>
						</view>
						<m-icon wh="34"
							:type="nowHeads['userid'] == item.userid?'icon-xuanzhong_-01':'icon-weixuanzhong_-01-01'"
							:color="nowHeads['userid'] == item.userid?'var(--theme)':'#999'"></m-icon>
					</view>
					<m-line spa='0'></m-line>
				</template>

			</m-block>
		</uni-popup>

	</m-layout>
</template>

<script>
	import { GoodsFirst, ShopCar_Add, CollectGoods, isCollect, CommentByGoods, GetShopCar } from '@/api/Goods.js';
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				item: {}, //商品信息
				attr: [],
				selectedUnit: {},
				heads: [],

				cartLoading: false,
				buycount: 1, //购买数量
				currentIndex: 0, //轮播图标记

				isCollection: false, // 是否收藏

				topStyle: 'rgba(255, 255, 255, 0)',
				topOpt: 0,
				tapScroll: [0, 0, 0, 0],
				scrollIdx: 0,
				scrollTop: 0,

				nowHeads: {
					trueName: '附近无货',
					userid: '',
				},

			};

		},
		computed: {
			...mapState({
				coinConfig: state => state.general.coinConfig,
				config: state => state.general.config,
				enum: state => state.general.enum,
				userinfo: state => state.user.userinfo,
				cartList: state => state.goods.cartList,
				cartLengh: state => state.goods.cartLengh,
				topNavHeight: state => state.general.topNavHeight,
				addressList: state => state.address.addressList,
				nowId: state => state.address.nowId
			}),
			address() {
				try {
					// return this.addressList[this.nowId] || '';
					let info = this.addressList.filter(item => {
						console.log(item)
						return item.id == this.nowId
					})
					return info[0]
				} catch (e) {
					return ""
					//TODO handle the exception
				}
			},
			goodsInfo() {
				let a = { ...this.item }
				if (this.selectedUnit?.id) {
					a = {
						...this.item,
						'price': this.selectedUnit['price'],
						'priceVip': this.selectedUnit['priceVip'],
						'stock': this.selectedUnit['stock'],
					}
				}
				return a
			},
			yftitle() {
				if (!this.goodsInfo.yf) {
					return '免运费'
				}
				return '￥' + this.goodsInfo.yf
			},
			defaultSelected() {
				let a = this.selectedUnit['value1Str'] || ''
				let b = this.selectedUnit['value2Str'] || ''
				let c = this.selectedUnit['value3Str'] || ''
				return [a, b, c].filter(x => x)
			},
			payButton() {
				// 库存不足
				if (this.goodsInfo['stock'] <= 0) return true
				// 没有团长
				if (!this.nowHeads?.userid) return true
				return false
			},
		},
		onLoad({ id, goodsId }) {
			this.goodsId = id || goodsId;
		},
		onShow() {
			this.init();
		},
		methods: {
			async init() {
				await this.GoodsFirst();

				await GetShopCar({ wards: this.goodsInfo['wards'] });
				// 延迟到下次DOM更新循环后 执行
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
				this.$nextTick(() => {
					// 获取页面数据  监听页面滑动位置
					this.getNode();
				}, 2);
			},

			// 收藏商品
			async collection() {
				const res = await CollectGoods({
					goodsId: this.goodsInfo.id,
					collect: !this.isCollection
				});
				if (res.success) {
					this.isCollection = !this.isCollection;
				}
			},
			// 添加购物车
			async addCart(type = 1) {
				if (this.attr.length > 1 && type == 1) {
					return this.$refs.popup.open();
				}

				let id = 0;
				if (this.attr['id'] != this.goodsInfo['id']) {
					id = this.attr['id']
				}

				this.cartLoading = true;
				const { success, msg } = await ShopCar_Add({
					gid: this.goodsId,
					attrid: id,
					count: this.buycount,
					headsUserid: this.nowHeads.userid,
					unitid: this.selectedUnit.id,
				});
				this.Toast(success ? '添加成功' : msg);
				await GetShopCar({ wards: this.goodsInfo['wards'] });
				this.cartLoading = false;
				this.$refs.popup.close();
			},
			// 立即购买
			goPay() {
				//下单时的ID  
				const goods = {
					...this.goodsInfo,
					buycount: this.buycount,
					...this.attr,
					gid: this.goodsInfo.id,
					headsUserId: this.nowHeads.userid,
					unitid: this.selectedUnit.id,
					unitName: this.defaultSelected.join('-'),
				};
				this.$store.commit('goods/SET_PAYGOODS', [goods]);
				this.$refs.popup.close();
				this.Jump('/pagesA/order/sureOrder/sureOrder');
			},
			// 商品是否收藏
			async isCollect() {
				const { data, success, msg } = await isCollect({
					id: this.goodsId
				});
				if (msg == '已收藏') {
					this.isCollection = true;
				} else {
					this.isCollection = false;
				}
			},
			async GoodsFirst() {
				try {
					const { data, success } = await GoodsFirst({
						id: this.goodsId
					});
					const { items, limit } = data
					this.item = items[0];
					this.attr = this.item['unit'] || []
					this.heads = this.item['heads']
					if (!this.nowHeads?.userid) {
						this.nowHeads = this['heads'][0]
					}


					console.log('this.nowHeads?.userid', this.nowHeads?.userid)
				} catch (e) {
					console.log('e', e)
				}
			},
			tapScrollFn(item) {
				// this.scrollIdx = item;
				uni.pageScrollTo({
					scrollTop: this.tapScroll[item],
					duration: 130
				});
			},
			async getNode() {
				// query.select('.rvaluate').fields({ rect: true });
				const query = uni.createSelectorQuery().in(this);
				query.select('.goodsDescription').fields({ rect: true });
				query.exec(data => {
					if (data.length > 0) {
						const a = data.map(item => {
							return item.top - 44 - this.topNavHeight;
						}, []);
						this.tapScroll = [0, ...a];
					}
				});
			},
		},
		onPageScroll({ scrollTop }) {
			this.tapScroll.forEach((item, idxx) => {
				if (item <= scrollTop + 1) {
					this.scrollIdx = idxx;
				}
			});
			let a = scrollTop / 2 / 100;
			this.scrollTop = scrollTop;
			console.log()
			this.topStyle = `rgba(255, 255, 255, ${a})`;
			this.topOpt = `${a}`;
		},
		onPullDownRefresh() {
			this.init();
		},

	}
</script>

<style lang="scss">
	.swiper-box {
		.swiper {
			min-height: 562rpx;

			video {
				width: 100%;
				height: 100%;
			}

			image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
		}
	}

	.image-box {
		image {
			width: 750rpx !important;
			height: 700rpx !important;
		}
	}

	.header-top {
		position: fixed;
		z-index: 9;
		top: var(--status-bar-height) 0 0;
		left: 0;
		width: 100%;

		.nav {
			padding: 20rpx 24rpx;
			box-sizing: border-box;
			background: rgba(255, 255, 255, 0);

			.mIcon {
				width: 42rpx;
				height: 42rpx;
				background: #ffffff;
				border-radius: 50%;
				text-align: center;
				line-height: 42rpx;
			}

			.right {
				view:nth-of-type(2) {
					margin-left: 20rpx;
				}
			}
		}

		.tables {
			flex: 1;
			opacity: 0;
			margin-left: 100rpx;
			display: grid;
			grid-template-columns: 1fr 1fr 1fr;
			text-align: center;

			text {
				position: relative;
				font-size: 28rpx;
				color: #999999;

				&:after {
					display: block;
					content: '';
					position: absolute;
					bottom: -10rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 0rpx;
					height: 4rpx;
					background: #fa2b47;
					transition: all 0.2s;
				}
			}

			.active {
				font-size: 30rpx;
				font-weight: bold;
				color: #fa2b47;

				&:after {
					width: 80rpx;
				}
			}
		}
	}


	.footer {
		position: fixed;
		width: 100%;
		background: #fff;
		box-sizing: border-box;
		bottom: 0;
		left: 0;
		padding: 24rpx;
		padding-bottom: calc(var(--window-bottom) + 24rpx);

		/* #ifdef MP-WEIXIN */
		.m-button {
			width: 100%;
			box-sizing: border-box;
		}

		/* #endif */

		.left {
			padding-right: 35rpx;

			.box2,
			.box1 {
				margin-right: 35rpx;
			}

			.box1 {
				padding: 0 !important;
				margin: 0 !important;
				border-width: 0 !important;
				border-color: unset !important;
				background: unset !important;
				cursor: not-allowed !important;
				border-image: initial;
				margin-right: 35rpx !important;

				&::after {
					display: none;
				}
			}

			.box {
				text-align: center;
				margin-top: 9rpx;

				text {
					display: block;
					font-size: 22rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #323232;
				}
			}
		}

	}


	.popup-goods {
		.goods-info {
			align-items: flex-start;

			.left {
				padding-right: 50rpx;
			}

			.right {
				align-items: flex-start;
				flex: 1;

				.h1 {
					align-items: flex-end;

					.des {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 30rpx;
						color: #333333;
					}

					.p2 {
						font-size: 30rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: var(--theme);
					}
				}

				.stock {
					padding: 20rpx 0;
					font-size: 26rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #999999;
				}

				.h2 {
					font-size: 26rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
				}

				.pop_txt {
					margin-left: 10rpx;
				}
			}
		}

		.spec-box {
			overflow-y: hidden;
			min-height: 500rpx;

			.swiper {
				min-height: 100rpx;
			}
		}

		.spec1 {
			margin-bottom: 20rpx;

			// border-bottom: 2rpx solid #f6f6f6;
			.title {
				background: #f5f5f5;
				border-radius: 14rpx;
				border: 2rpx solid #f6f6f6;
				padding: 15rpx 15rpx;

				.goodsGuiGeName {
					margin-right: 20rpx;
					display: inline-block;
					flex: 1;
					font-size: 26rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #666;
				}

				.m-number {
					color: #999999 !important;
					font-weight: normal !important;
				}

				.integral {
					color: #7c7c7c;
					font-size: 24rpx;
				}


			}

			.active {
				background: #f5f5f5;
				border: 2rpx solid var(--theme);

				.m-number {
					color: var(--theme) !important;
					// font-weight: 600 !important;
				}

				.goodsGuiGeName {
					color: var(--theme) !important;
				}
			}

			.spec1-main {
				max-height: 500rpx;
				overflow-y: scroll;
			}
		}

		.amount {
			padding: 10rpx 0 60rpx;
		}

		.btn-box {}
	}

	.popup-heads {
		.li {
			padding: 40rpx 0;
		}
	}
</style>